<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>项目构建页面</title>

</head>
<body>
<h2>项目构建表单</h2>
<form onsubmit="submitForm(event)">
    <label for="projectName">项目名称:</label><br>
    <input type="text" id="projectName" name="projectName"><br><br>

    <label for="projectCode">项目代码:</label><br>
    <input type="text" id="projectCode" name="projectCode"><br><br>

    <label for="packageCode">包名:</label><br>
    <input type="text" id="packageCode" name="packageCode"><br><br>

    <label for="file">上传文件:</label><br>
    <input type="file" id="file" name="file" multiple><br><br>

    <input type="submit" value="提交构建">
</form>

<script>
    async function submitForm(event) {
        event.preventDefault();

        const formData = new FormData(document.querySelector("form"));

        const response = await fetch("/build", {
            method: "POST",
            body: formData
        });

        const contentType = response.headers.get("content-type");

        if (contentType && contentType.includes("application/json")) {
            const result = await response.json();
            alert(result.msg || "未知错误");
        } else {

            const disposition = response.headers.get('Content-Disposition');
            let fileName = getFileNameFromContentDisposition(disposition) || 'download.zip';


            const blob = await response.blob();
            const downloadUrl = window.URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = downloadUrl;
            a.download = fileName;
            document.body.appendChild(a);
            a.click();
            a.remove();
        }
    }


    function getFileNameFromContentDisposition(header) {
        if (!header) return null;

        // 优先匹配 filename*=utf-8''
        const utf8FilenameRegex = /filename\*=UTF-8''([\w%\-\.]+)/i;
        const asciiFilenameRegex = /filename="?([^"]+)"?/;

        let utf8Matches = header.match(utf8FilenameRegex);
        if (utf8Matches && utf8Matches[1]) {
            try {
                return decodeURIComponent(utf8Matches[1]);
            } catch (e) {
                return unescape(utf8Matches[1]);
            }
        }

        // 回退到普通 filename=
        const asciiMatches = header.match(asciiFilenameRegex);
        if (asciiMatches && asciiMatches[1]) {
            return asciiMatches[1];
        }

        return null;
    }
</script>
</body>
</html>
